/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // 递归实现
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        postorder(root,res);
        return res;
    }
    public void postorder(TreeNode root, List<Integer> res){
        if(null == root){
            return;
        }
        postorder(root.left, res);
        postorder(root.right, res);
        res.add(root.val);
    }
    // 迭代实现
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        if(root != null){
            Deque<TreeNode> s1 = new ArrayDeque<>();
            Deque<TreeNode> s2 = new ArrayDeque<>();
            s1.push(root);
            while(!s1.isEmpty()){
                root = s1.pop();
                s2.push(root);
                if(root.left != null){
                    s1.push(root.left);
                }
                if(root.right != null){
                    s1.push(root.right);
                }
            }
            while(!s2.isEmpty()){
                list.add(s2.pop().val);
            }
        }
        return list;
    }
}